<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo前后端接口验证</title>
    <script src="./axios.js"></script>
</head>

<body>
    <div>
        <h3>数据初始化</h3>
        <button onclick="initData()">初始化user permission 及关联关系</button>
    </div>

    <h3>用户鉴权</h3>
    <div style="display: flex;">
        <button onclick="getUserId()">获取用户鉴权信息</button>&nbsp;&nbsp;&nbsp;
        <button onclick="checkUser()">校验用户session信息是否正确</button>&nbsp;&nbsp;&nbsp;
        <button onclick="getToken()">设置token</button>
    </div>

    <h3>图片文件处理</h3>
    <div style="display: flex;">
        <form enctype="multipart/form-data">
            <input type="file" accept=".png,.PNG,.JPEG,.jpeg" name="图片上传" onchange="uploadFile(event)">
        </form>
        <div>
            <button onclick="downloadPic()">下载图片(blob下载)</button>
        </div>
        &nbsp;&nbsp;&nbsp;
        <div>
            <button onclick="downloadStream()">下载图片(stream下载)</button>
        </div>
    </div>

    <h3>测试系列接口</h3>
    <div style="display: flex;">
        <button onclick="getHomeId()">测试接口 /home/:id </button> &nbsp;&nbsp;&nbsp;
        <button onclick="getCreateId()">测试接口 /home/create </button> &nbsp;&nbsp;&nbsp;
        <button onclick="pipeValite()">测试管道验证接口 /home/pipe </button> &nbsp;&nbsp;&nbsp;
        <button onclick="guardValite()">测试守卫接口 /home/guard </button>
    </div>

    <h3>用户信息增删查改</h3>
    <div style="display: flex;">
        <button onclick="getUserByName()">根据用户名称获取用户信息</button>&nbsp;&nbsp;&nbsp;
    </div>

    <h3>实现登陆注册功能</h3>
    <div style="display: flex; flex-direction: column;">
        <div>
            <h4>登录框</h4>
            <form action="">
                账号: <input type="text" name="user" id="username"><br>
                密码: <input type="text" name="password" id="password">
            </form>
            <button onclick="login()"> 登录</button>
        </div>&nbsp;&nbsp;&nbsp;

        <div>
            <button onclick="register()">注册</button>
        </div>&nbsp;&nbsp;&nbsp;
    </div>
</body>
<script>
    let sessionInfo = '';
    let refreshing = false;
    const queue = [];
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    // 处理返回结果：
    axios.interceptors.response.use(
        // 返回数据
        (response) => {
            return response;
        },
        // 处理返回的错误信息
        async (error) => {
            let {
                data,
                config
            } = error.response;

            if (refreshing) {
                return new Promise((resolve) => {
                    queue.push({
                        config,
                        resolve
                    });
                });
            }

            if (data.status === 401) {
                refreshing = true;
                const res = await refreshToken();
                refreshing = false;
                if (res.status === 200) {
                    queue.forEach(({
                        config,
                        resolve
                    }) => {
                        resolve(axios(config))
                    })

                    return axios(config);
                } else {
                    alert('登录过期，请重新登录');
                    return Promise.reject(res.data)
                }
            } else {
                console.log('error======>', error);
                return error.response;
            }
        }
    )

    // 重新刷新请求token
    async function refreshToken() {
        const refreshToken = localStorage.getItem('refresh_token');
        const res = await axios.get(`/user/refresh/${refreshToken}`);
        localStorage.setItem('access_token', res.data.access_token || '');
        localStorage.setItem('refresh_token', res.data.refresh_token || '');
        return res;
    }
    // 获取用户session 信息：
    async function getUserId() {
        const res = await axios.get('/user/getUserId');
        sessionInfo = res.data.session || '';
        alert(`获取到session: ${sessionInfo}`)
    }

    //  校验用户session信息是否正确
    async function checkUser() {
        const data = {
            sessionInfo,
            userName: 'kobe'
        }
        const res = await axios.post('/user/checkUser', data);
        alert(`${res.data.message}`);
    }

    async function getToken() {
        const res = await axios.get('/token');
        // 取到token 值就缓存，并在请求头带上
        if (res.data.code === 200) {
            localStorage.setItem('token', res.data.data);
            // 本地设置token 后带入请求头
            axios.defaults.headers.common['Authorization'] = localStorage.getItem('token') || '';
        }
    }

    // 图片上传
    async function uploadFile(e) {
        const formFile = new FormData();
        const file = e.target.files[0];
        formFile.append('file', file);
        const res = await axios.post('/upload/pic', formFile);
        if (res.data.url) {
            alert(`图片上传成功，获取图片地址为：${res.data.url}`)
        }
    }

    // 图片下载
    async function downloadPic() {
        const res = await axios.get('/upload/exportPic', {
            responseType: 'blob'
        });
        if (res.data) {
            const blob = new Blob([res.data])
            const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
            if ("download" in document.createElement('a')) {
                let link = document.createElement('a');
                link.style.display = 'none';
                link.href = imageUrl;
                link.setAttribute('download', '测试图片.png');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }

    // stream 下载
    async function downloadStream() {
        const res = await axios.get('/upload/stream', {
            responseType: 'blob'
        });
        if (res.data) {
            const blob = new Blob([res.data])
            const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
            if ("download" in document.createElement('a')) {
                let link = document.createElement('a');
                link.style.display = 'none';
                link.href = imageUrl;
                link.setAttribute('download', '图片集合.zip');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }

    //  测试接口 /create/:id
    async function getHomeId() {
        const res = await axios.get('/home/100');
        if (res.data.code === 200) {
            alert(` 测试接口 /home/:id 成功, ${res.data.data}`)
        }
    }

    // 测试接口 /home/create
    async function getCreateId() {
        const data = {
            name: 'llz',
            age: 30
        };
        const res = await axios.post('/home/create', data);
        if (res.data.code === 200) {
            alert(`测试接口 /home/create 成功, ${res.data.data}`)
        }
    }

    // 获取管道验证接口 /home/pipe
    async function pipeValite() {
        const data = {
            name: 'llz',
            age: 30
        };
        const res = await axios.post('/home/pipe', data);
        if (res.data.code === 200) {
            alert(`测试管道验证接口 /home/pipe 成功, ${res.data.data}`)
        }
    }

    // 守卫接口
    async function guardValite() {
        const res = await axios.get('/home/guard', {
            params: {
                role: 'admin'
            }
        });
        if (res.data.code === 200) {
            alert(`守卫验证成功, 获取守卫信息：${res.data.data}`)
        }
    }

    // 根据用户名称获取用户信息
    async function getUserByName() {
        const username = document.querySelector('#username').value || '';
        if (!username) {
            alert('用户名不能为空')
            return;
        }

        const res = await axios.get(`/user/getUserByName/${username}`);
        if (res.data.code === 200) {
            alert(`用户信息获取成功`)
        } else {
            alert(`${res.data.data}`)
        }

    }

    // 新用户注册
    async function register() {
        const username = document.querySelector('#username').value || '';
        const password = document.querySelector('#password').value || '';
        if (!username || !password) {
            alert('用户名或者密码不能为空')
            return;
        }
        const user = {
            username,
            password
        }
        const res = await axios.post('/user/register', user);
        if (res.data.code === 200) {
            alert(`${res.data.data}`)
        } else {
            alert(`${res.data.data}`)
        }
    }

    // 用户登录
    async function login() {
        const username = document.querySelector('#username').value || '';
        const password = document.querySelector('#password').value || '';
        if (!username || !password) {
            alert('用户名或者密码不能为空')
            return;
        }
        const user = {
            username,
            password
        }
        const res = await axios.post('/user/login', user);
        if (res.data.code === 200) {
            // 登录成功之后，设置 token 后带入请求头
            axios.defaults.headers.common['Authorization'] = res.data.access_token;
            // 本地缓存token 信息：
            localStorage.setItem('access_token', res.data.access_token);
            localStorage.setItem('refresh_token', res.data.refresh_token);
            alert(`用户登陆成功，该用户为： ${res.data.data.username}, 获取 access_token 为: ${res.data.access_token}`)
        } else {
            alert(`用户登陆失败`)
        }
    }

    // 初始化数据及关联表
    async function initData() {
        const res = await axios.get('/user/init');
        if (res.data.code === 200) {
            alert(`${res.data.data}`)
        }
    }
</script>

</html>